package com.Ugent.Minerva;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.Ugent.Minerva.CalendarView.OnMonthChangedListener;
import com.Ugent.Minerva.CalendarView.OnSelectedDayChangedListener;



public class Agenda extends Activity {
    TextView gebruiker;
    private Student s1 = null;
    private CalendarView calendar;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.agenda);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
       
        s1 = (Student) getIntent().getSerializableExtra("student");
        gebruiker = (TextView) findViewById(R.id.gebruiker);
        gebruiker.setText(s1.getName());

        //set calenderview
        calendar = (CalendarView) findViewById(R.id.calendar_view);

		calendar.setOnMonthChangedListener(new OnMonthChangedListener() {
			public void onMonthChanged(CalendarView view) {
				markDays();
			}
		});

		calendar.setOnSelectedDayChangedListener(new OnSelectedDayChangedListener() {
			public void onSelectedDayChanged(CalendarView view) {
				//get calendarEvents from course
				@SuppressWarnings("unchecked")
				ArrayList<CalendarEvent> agenda = (ArrayList<CalendarEvent>) getIntent().getSerializableExtra("calendar");
				ArrayList<String> startDate = new ArrayList<String>();
				//arraylist with events per selected day
				ArrayList<CalendarEvent> dayEvents = new ArrayList<CalendarEvent>();
				AgendaAdapter adapter = null;
				ListView lv = new ListView(Agenda.this);
				
				//get all startdates for a course
 				for (int i = 0; i<agenda.size(); i++){
					startDate.add(agenda.get(i).getStart());
				}
				
 				//get exact time of selected day 
				Calendar cal = view.getSelectedDay();
				int month1 = cal.get(Calendar.MONTH);
				String month = Integer.toString(month1+1);
				if (month.length() == 1){
					month = "0"+month;
				}
				int year1 = cal.get(Calendar.YEAR);
				String year = Integer.toString(year1);
				int day1 = cal.get(Calendar.DAY_OF_MONTH);
				String day = Integer.toString(day1);
				if (day.length() == 1){
					day = "0"+day;
				}
				//exact time
				String date = year+"-"+month+"-"+day;
				
				//build dayEvents where events have same startDate as exact date selected day
				for (int i = startDate.size()-1; i>=0 ;i--){
					String t = startDate.get(i);
					String date2 = Facade.getDate2(t);
					if (date2.equals(date)){			
						dayEvents.add(agenda.get(i));		
					}
				}	
				
				//setup listview for dayEvents
				adapter = new AgendaAdapter (Agenda.this, R.layout.agendalist, dayEvents);					
				lv.setAdapter(adapter);
				lv.setVerticalFadingEdgeEnabled(false);	
				//give listview to calenderview
				View[] v = new View[1];
				v[0]= lv;
				view.setListViewItems(v);
			}
		});

		markDays();
		
	}
    
	private void markDays() {
		
		@SuppressWarnings("unchecked")
		ArrayList<CalendarEvent> agenda = (ArrayList<CalendarEvent>) getIntent().getSerializableExtra("calendar");
		ArrayList<String> startDate = new ArrayList<String>();
		for (int i = 0; i<agenda.size(); i++){
			startDate.add(agenda.get(i).getStart());
		}
		for (int i = 0; i<startDate.size();i++){
			String date = Facade.getDate(i, startDate);
			int year = Facade.getYear(date);
			int month = Facade.getMonth(date);
			int day = Facade.getDay(date);
			//set days with CalendarEvents blue
			calendar.setDaysWithEvents(new CalendarDayMarker[] { new CalendarDayMarker( year, month-1, day, Color.BLUE) });
		}
		//make current day red
		calendar.setDaysWithEvents(new CalendarDayMarker[] { new CalendarDayMarker(Calendar.getInstance(), Color.RED) });
		
		
	}


    public void clickHandler(View v){       
        
        startActivity(new Intent(getApplicationContext(), Account.class));

    }
    
    //adapter for listview
    private class AgendaAdapter extends ArrayAdapter<CalendarEvent> {

        private ArrayList<CalendarEvent> items;

        public AgendaAdapter(Context context, int textViewResourceId, ArrayList<CalendarEvent> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.agendalist, null);
                }
                final CalendarEvent c = items.get(position);
                if (c != null) {
                        TextView tt = (TextView) v.findViewById(R.id.toptext);
                        TextView bt = (TextView) v.findViewById(R.id.bottomtext);
                        TextView rt = (TextView) v.findViewById(R.id.date);
                        
                        //add button to export event to native calendar
                        Button add = (Button) v.findViewById(R.id.btn_add);
                        add.setOnClickListener(new OnClickListener() {
                    	    @Override
                    	    public void onClick(View v) {
                    	    	//get version number of device
                    	    	String version = Build.VERSION.RELEASE;
                    	    	String version1 = version.substring(0,1);
                    	    	String version2 = version.substring(2,3);
                    	    	int vers = Integer.parseInt(version1+version2);
                    	    	
                    	    	//query database for calendar 
                    	    	Cursor cursor;
                    	    	//android >=2.2
            					if (vers >= 22){
            						cursor=getContentResolver().query(Uri.parse("content://com.android.calendar/calendars"), new String[]{"_id", "displayname"}, null, null, null);
            					}
            					//android <2.2
            					else {
            						cursor=getContentResolver().query(Uri.parse("content://calendar/calendars"), new String[]{"_id", "displayname"}, null, null, null);
            					}
            					
            					cursor.moveToFirst();
            					// Get calendars name
            					String calendarNames[] = new String[cursor.getCount()];
            					// Get calendars id
            					int [] calendarId = new int[cursor.getCount()];
            							
            					for (int i = 0; i < calendarNames.length; i++){
            						
            						calendarId[i] = cursor.getInt(0);
            						calendarNames[i] = cursor.getString(1);
            						cursor.moveToNext();
            					}
            					
            					//put information 
            					ContentValues contentEvent = new ContentValues();
            					contentEvent.put("calendar_id", calendarId[0]);                                                   
            					contentEvent.put("title", c.getTitle());   
            					Spanned des = Html.fromHtml(c.getDescription());
            					contentEvent.put("description", des.toString());  
            					contentEvent.put("visibility", 0);
            					
	            					//get startdate in millisecondes
	            					String start = c.getStart();
	    							int year = Facade.getYearAdd(start);
	    							int month = Facade.getMonthAdd(start);
	    							int day = Facade.getDayAdd(start);
	    							int hour = Facade.getHour(start);
	    							int minute = Facade.getMinute(start);

	    							GregorianCalendar d = new GregorianCalendar (year, month-1, day, hour, minute);
	    							long dtstart = d.getTime().getTime(); 						
     							                                                       
 							
	     							//get enddate in millisecconds
	     							String end = c.getEnd();
	    							int yearEnd = Facade.getYearAdd(end);
	    							int monthEnd = Facade.getMonthAdd(end);
	    							int dayEnd = Facade.getDayAdd(end);
	    							int hourEnd = Facade.getHour(end);
	    							int minuteEnd = Facade.getMinute(end);
	    							GregorianCalendar dEnd = new GregorianCalendar (yearEnd, monthEnd-1, dayEnd, hourEnd, minuteEnd);
	    							long dtend = dEnd.getTime().getTime();
	    						
	    						contentEvent.put("dtstart", dtstart);   
    							contentEvent.put("dtend", dtend); 

    							
            							
    							Uri eventsUri;
    							if (vers >= 22){
    								eventsUri = Uri.parse("content://com.android.calendar/events");  
            					}
            					else {
            						eventsUri = Uri.parse("content://calendar/events");  
            					} 
    							//add event
    							getContentResolver().insert(eventsUri, contentEvent);    	
    							cursor.close();
                    	   }
                    	});

                        if (tt != null) {
                              tt.setText(c.getTitle());                            
                        }
                        if(bt != null){	
                              bt.setText(Html.fromHtml(c.getDescription()));
                        }
                        if(rt != null){
                        	String start = Facade.getHourDate(c.getStart());
                        	String end = Facade.getHourDate(c.getEnd());
                        	String date = start+" - "+end;
                            rt.setText(date);
                        }    
                }
                return v;
        }
    }

           
}  